<?php

namespace App\Http\Controllers;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Request;

class PayParamsController
{
    public $httpRequestUrl = "https://www.payxiao.com/payApi";
    //   public $httpRequestUrl = "http://120.27.18.75:7046";
    public $httpRequestUrlAgent = "http://agentapi.xiaojuhepay.com";

    public function isbuild(Request $request)
    {
        $client = new Client();
        // 判断当前设备是否绑定终端
        if ($request::query("buildSn") != null && $request::query('buildSn') != " ") {
            $body = [
                'terId' => $request::query('terId'),
                'code' => $request::query('code'),
            ];
            $options = [
                'headers' => [
                    'Content-Type' => 'application/json;charset=UTF-8'
                ],
                'body' => json_encode($body)
            ];
            $buildSn = $client->post($this->httpRequestUrlAgent . "/laiqianle/terminal/setsn", $options);
            return json_decode($buildSn->getBody()->getContents());
        }
        $red = $request::root() . '/getParams/?code=' . $request::query('code');
        return redirect($red);
    }

    public function isbuildTest(Request $request)
        {
            $client = new Client();
            // 判断当前设备是否绑定终端
            if ($request::query("buildSn") != null && $request::query('buildSn') != " ") {
                $body = [
                    'terId' => $request::query('terId'),
                    'code' => $request::query('code'),
                ];
                $options = [
                    'headers' => [
                        'Content-Type' => 'application/json;charset=UTF-8'
                    ],
                    'body' => json_encode($body)
                ];
                $buildSn = $client->post($this->httpRequestUrlAgent . "/laiqianle/terminal/setsn", $options);
                return json_decode($buildSn->getBody()->getContents());
            }
            $red = $request::root() . '/getParamsTest/?code=' . $request::query('code');
            return redirect($red);
        }


    /**
     * 获取参数
     * @param Request $request
     * @throws GuzzleException
     */
    public function getParams(Request $request)
    {

        if ($request::query('code') == null) {
            return redirect($request::root() . "/term.html");
        }

        // 对路径跳转进项设置
        $redPath = "/getpay?";
        $agent = $request::header('user-agent');
        if (preg_match('/AlipayClient/', $agent)) {
            $redPath = "/getpayDe?";
        } elseif (preg_match('/com.unionpay.mobilepay/', $agent)) {
            $redPath = "/getpayDe?";
        }elseif (preg_match('/com.unionpay.chsp/', $agent)) {
            $redPath = "/getpayDe?";
        }


        // 获取支付参数
        $option = [
            'headers' => [
                'Content-Type' => 'application/json;charset=UTF-8'
            ]
        ];
        $client = new Client();
        $req = $client->get($this->httpRequestUrl . "/system/codeparams/" . $request::query('code'), $option);
        $params = json_decode($req->getBody()->getContents());
        // var_dump($params);
        // 获取不到终端支付参数错误处理
        if ($params->code == 500) {
            return redirect($request::root() . "/mer.html");
        }

        $red = $request::root() . $redPath . 'merName=' . urlencode($params->data->merchantName) . '&terName='
            . urlencode($params->data->merchantName) . '&sn=' . $params->data->outDeviceSn . '&tenant_no=' . $params->data->outMerchantNo
            . '&is_remarks=' . $params->data->is_remarks;
        return redirect($red);
    }

    /**
         * 获取参数
         * @param Request $request
         * @throws GuzzleException
         */
        public function getParamsTest(Request $request)
        {

            if ($request::query('code') == null) {
                return redirect($request::root() . "/term.html");
            }

            // 对路径跳转进项设置
            $redPath = "/getpayTest?";
            $agent = $request::header('user-agent');
            if (preg_match('/AlipayClient/', $agent)) {
                $redPath = "/getpayDe?";
            } elseif (preg_match('/com.unionpay.mobilepay/', $agent)) {
                $redPath = "/getpayDe?";
            }elseif (preg_match('/com.unionpay.chsp/', $agent)) {
                $redPath = "/getpayDe?";
            }


            // 获取支付参数
            $option = [
                'headers' => [
                    'Content-Type' => 'application/json;charset=UTF-8'
                ]
            ];
            $client = new Client();
            $req = $client->get($this->httpRequestUrl . "/system/codeparams/" . $request::query('code'), $option);
            $params = json_decode($req->getBody()->getContents());
            // var_dump($params);
            // 获取不到终端支付参数错误处理
            if ($params->code == 500) {
                return redirect($request::root() . "/mer.html");
            }

            $red = $request::root() . $redPath . 'merName=' . urlencode($params->data->merchantName) . '&terName='
                . urlencode($params->data->merchantName) . '&sn=' . $params->data->outDeviceSn . '&tenant_no=' . $params->data->outMerchantNo
                . '&is_remarks=' . $params->data->is_remarks;
            return redirect($red);
        }

    /***
     * 创建公众号支付地址
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function createdParams(Request $request)
    {
        $user = session('wechat.oauth_user.default'); // 拿到授权用户资料
        $params = http_build_query($request::query());
        $params = $params . "&openid=" . $user['id'];
        return redirect($request::root() . "/cashier.html?" . $params);
    }

   /***
     * 创建公众号支付地址 d
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function createdParamsTest(Request $request)
    {
        $user = session('wechat.oauth_user.default'); // 拿到授权用户资料
        $params = http_build_query($request::query());
        $params = $params . "&openid=" . $user['id'];
        return redirect($request::root() . "/cashier-1.html?" . $params);
    }


    /***
     * 创建公众号支付地址
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function createdParamsAliYun(Request $request)
    {
        $params = http_build_query($request::query());
        return redirect($request::root() . "/cashier.html?" . $params);
    }


    /**
     * 获取支付平台
     */
    public function getPayPlatform(Request $request)
    {

        // 获取支付参数
        $option = [
            'headers' => [
                'Content-Type' => 'application/json;charset=UTF-8'
            ]
        ];
        $client = new Client();
        $req = $client->get($this->httpRequestUrl . "/system/codeparams/mersn/" . $request::post('mersn'), $option);
        $params = json_decode($req->getBody()->getContents());
        if ($params == null) {
            return "error";
        }
        $agent = $request::header('user-agent');
        if (preg_match('/MicroMessenger/', $agent)) {
            if ($params->data->wxAppId == null && $params->data->wxServiceNo == null) {
                return 1;
            } else {
                return 2;
            }
        } elseif (preg_match('/AlipayClient/', $agent)) {
            return 5;
        } elseif (preg_match('/com.unionpay.mobilepay/', $agent)) {
            return 8;
        }elseif (preg_match('/com.unionpay.chsp/', $agent)) {
            return 8;
        }
    }

    /**
     * @throws GuzzleException
     */
    public function pay(Request $request)
    {
        $client = new Client();
        $params = [
            "device_type" => 3,
            "tradeMoney" => $request::post('tradeMoney'),
            "payType" => $request::post('payType'),
            "sn" => $request::post('sn'),
            "tenant_no" => $request::post('tenant_no'),
            'openid' => $request::post('openid') ?? null,
            'remarks' => $request::post('remark'),
            'appid' => "wxd435897cbdb1e0f8"
        ];
        $option = [
            'headers' => [
                'Content-Type' => 'application/json;charset=UTF-8'
            ],
            'body' => json_encode($params)
        ];
        $req = $client->post($this->httpRequestUrl . "/payweb/send", $option);
        return json_decode($req->getBody()->getContents());
    }

    /**
     * 获取支付平台
     */
    public function getPayPlatformtest(Request $request)
    {
        $agent = $request::header('user-agent');
        var_dump($agent);
    }
}
